const {
    db,
    sqlExec,
    sqlExecInTransaction,
    startTransaction,
    commitTransaction,
    rollbackTransaction
} = require('../db/mysql57');
const minio = require('../db/minio');

const userinfoDao = {
    async getUserInfo(uid) {
        let sql = `select
                userIcon,
                username,
                phone,
                college,
                major,
                level,
                bio,
                registerTime
            from User
            where id = ? LIMIT 1`;
        let data = [ uid ];
        return sqlExec(sql, data);
    },
    async updateUserInfo(uid, username, college, major, level, bio) {
        let sql = `update User set 
                username = ?,
                college = ?,
                major = ?,
                level = ?,
                bio = ?
            where id = ?`;
        let data = [username, college, major, level, bio, uid];
        return sqlExec(sql, data);
    },
    /*
     * 获取 专注时长、投递数、收藏数 的数据
     */
    async getHomePageNeedData(uid) {
        let sql = `select
                (select SUM(duration) from FoucsCheckin where uid = ?) as total_duration,
                (select
                    COUNT(*)
                from ResumeSubmissions as rs
                left join Resume as r on rs.resumeId = r.id
                where r.uid = ? and rs.isDel = 'false') as resume_submission_count,
                (select COUNT(*) from JobFavorites where uid = ?) as favorite_count`;
        let data = [ uid, uid, uid ];
        return sqlExec(sql, data);
    },
    /*
     * 上传用户头像图片
     */
    async updateUserIcon(uid, buffer) {
        // 尝试开启事务
        let connection;
        let result;
        let browser = 'hcyj-usericon';
        let uri = '';
        try {
            connection = await startTransaction();
        } catch (error) {
            return { success: false, msg: '数据库连接失败' };
        }
        // 往 PublicImg 表中插入数据
        try {
            let status = '待上传';
            let sql = `insert into PublicImg (browser, uri, status) VALUES (?, ?, ?)`;
            let data = [browser, uri, status];
            result = await sqlExecInTransaction(connection, sql, data);
        } catch (error) {
            await rollbackTransaction(connection);
            return { success: false, msg: '数据库连接失败' };
        }
        // 往 MinIO 中上传图片（这个操作应该要封装到 minio 驱动里，后续修改）
        try {
            uri = `${result.insertId}.jpg`;
            await new Promise((resolve, reject) => {
                minio.minio.putObject(browser, uri, buffer, buffer.length, async function (err, etag) {
                    if (err) {
                        reject(err);
                        return ;
                    }
                });
                resolve(true);
            });
        } catch (err) {
            await rollbackTransaction(connection);
            return { success: false, msg: '上传对象存储服务失败' };
        }
        // 更新 mysql 数据库中 图片的上传状态
        try {
            let sql = `update PublicImg set status = ?, uri = ? where id = ?`;
            let data = ['已完成', uri, result.insertId];
            await sqlExecInTransaction(connection, sql, data);
        } catch (err) {
            await rollbackTransaction(connection);
            return { success: false, msg: '操作数据库失败' };
        }
        // 将用户当前的userIcon存储到历史头像表里
        try {
            let sql = `insert into HistoryUserIcon(
                uid, imgId
            ) VALUES (?, (select userIcon from User where id = ? LIMIT 1))`;
            let data = [uid, uid];
            await sqlExecInTransaction(connection, sql, data);
        } catch (err) {
            await rollbackTransaction(connection);
            return { success: false, msg: '操作数据库失败' };
        }
        // 修改用户当前的userIcon
        try {
            let sql = `update User set userIcon = ? where id = ?`;
            let data = [result.insertId, uid];
            await sqlExecInTransaction(connection, sql, data);
        } catch (err) {
            await rollbackTransaction(connection);
            return { success: false, msg: '操作数据库失败' };
        }
        // 提交事务
        try {
            commitTransaction(connection);
        } catch (error) {
            await rollbackTransaction(connection);
            return { success: false, msg: '事务提交失败' };
        }
        // 返回数据
        return { success: true, msg: "上传图片成功", data: result.insertId };
    }
};

module.exports = userinfoDao;